package com.lxk.util;

import com.lxk.dao.AuctionMapper;
import com.lxk.dao.OrdersMapper;
import com.lxk.pojo.Auction;
import com.lxk.pojo.Orders;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 拍卖定时降价任务
 * @author JohnSoybean
 * @time 2020年3月13日
 */
public class AuctionPriceTimerTask extends TimerTask {
    private Timer timer;
    private Integer auctionId;
    private Date endTime;
    private BigDecimal bottomPrice;
    private BigDecimal priceSpan;
    private BigDecimal nowPrice;
    
    public AuctionPriceTimerTask(Timer timer) {
        this.timer = timer;
    }
    
    public AuctionPriceTimerTask(Timer timer, Integer auctionId, Date endTime, BigDecimal originPrice, BigDecimal bottomPrice, BigDecimal priceSpan) {
        this.timer = timer;
        this.auctionId = auctionId;
        this.endTime = endTime;
        this.bottomPrice = bottomPrice;
        this.nowPrice = originPrice.add(priceSpan);
        this.priceSpan = priceSpan;
    }

    @Override
    public void run() {
        try {
            //当执行到小于底价，或到达结束时间，或已有人购买，程序结束
            Date nowTime = new Date();
            if(nowTime.after(endTime)) {
            	this.timer.cancel();
            	System.out.println("#### 结束时间到，拍卖任务结束 ####");
            	return;
            }
            nowPrice = nowPrice.subtract(priceSpan);
            if (nowPrice.compareTo(bottomPrice) < 0) {
                this.timer.cancel();
                System.out.println("#### 低于底价，降价任务结束 ####");
                return;
            }
            AuctionMapper auctionMapper = SpringContextHolder.getBean(AuctionMapper.class);
            OrdersMapper ordersMapper = SpringContextHolder.getBean(OrdersMapper.class);
            Auction auction = auctionMapper.selectByPrimaryKey(auctionId);
            //判断是否被手动停止
            if(nowTime.after(auction.getAuctionEndTime())) {
                this.timer.cancel();
                System.out.println("#### 已手动结束，拍卖任务结束 ####");
                return;
            }
            if(auction.getWxUserId()!=null&&auction.getOrdersId()!=null) {
            	Orders orders = ordersMapper.selectByPrimaryKey(auction.getOrdersId());
            	Integer status = orders.getOrdersStatus();
            	//判断是否支付成功
            	if(status==1||status==2||status==3) {
            		this.timer.cancel();
                    System.out.println("#### 已被拍下，拍卖任务结束 ####");
                    return;
            	}
            }
            //修改数据库
            auction.setAuctionNowPrice(nowPrice);
            auctionMapper.updateByPrimaryKeySelective(auction);
            System.out.println("******完成一次降价进程"+", 现价："+nowPrice+"******");
        }catch(Exception e) {
        	e.printStackTrace();
        	System.out.println("降价拍卖进程出现异常");
        	this.timer.cancel();
        }
    }
}
